<?php

namespace App\Jobs;

use App\Model\User;
use App\Repository\UserRepository;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SaveSubscribeUser implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $openId;

    /**
     * Create a new job instance.
     *
     * @param $openId
     */
    public function __construct($openId)
    {
        $this->openId = $openId;
    }

    /**
     * Execute the job.
     *
     */
    public function handle()
    {
        $userInfo = app('wechat')->user->get($this->openId);

        User::withTrashed()->updateOrCreate(['open_id' => $this->openId], [
            'subscribed_at' => Carbon::createFromTimestamp($userInfo->subscribe_time)->toDateTimeString(),
            'nickname' => $userInfo->nickname,
            'avatar' => $userInfo->headimgurl
        ])->restore();

    }
}
